package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmMaterial;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.locks.Condition;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-21
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
@Autowired
private IWmUserService wmUserService;
    @Autowired
    @Lazy
    private IAuditSrevice auditService;



    @Override
    public ResponseResult findPageByName(NewsDto newsDto) {

        IPage<WmNews> page=new Page<>(newsDto.getPage(),newsDto.getSize());

        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        if(newsDto.getTitle()!=null){
            query.like(WmNews::getTitle,newsDto.getTitle());
        }
        System.out.println("--------------------->"+newsDto.getPage());
        IPage<WmNews> iPage = this.page(page, query);

        List<WmNews> iPageRecords = iPage.getRecords();
        for (WmNews news : iPageRecords) {
            Integer userId = news.getUserId();
            WmUser wmUser = wmUserService.getById(userId);
            news.setAuthorName(wmUser.getName());

        }

        long total = iPage.getTotal();
        PageResponseResult<List<WmNews>> responseResult = new PageResponseResult<>(newsDto.getPage(), newsDto.getSize(), total, iPageRecords);

        return responseResult;
    }
//查询新闻的详情
    @Override
    public ResponseResult listById(Integer id) {
//        进行非空判断
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        根据id查询新闻信息
        WmNews wmNews = this.getById(id);
        Integer userId = wmNews.getUserId();
        WmUser wmUser = wmUserService.getById(userId);
        wmNews.setAuthorName(wmUser.getName());


        return ResponseResult.okResult(wmNews);
    }

    @Override
    public ResponseResult find(WmNewsPageDto dto) {
        IPage<WmNews> page=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        if(dto.getStatus()!=null){
            query.eq(WmNews::getStatus,dto.getStatus());

        }
        if(dto.getChannelId()!=null){
            query.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if(dto.getKeyword()!=null){
            query.like(WmNews::getTitle,dto.getKeyword());
        }
        if(dto.getBeginPubDate()!=null){
            query.gt(WmNews::getPublishTime,dto.getBeginPubDate());

        }
        if (dto.getEndPubDate()!=null){
            query.lt(WmNews::getPublishTime,dto.getEndPubDate());

        }
//        得是当前用户的
        User user = MediaThreadLocalUtil.get();
//        根据发布时间进行降序
        query.eq(WmNews::getUserId,user.getUserId());
        query.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> iPage = this.page(page, query);
        PageResponseResult<List<WmNews>> result = new PageResponseResult<>(dto.getPage(), dto.getSize(), iPage.getTotal(), iPage.getRecords());

        return result;
    }
//    文章的添加


    @Override
    public ResponseResult submit(WmNewsDto dto) {
//        获取县城中的用户
        User user = MediaThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

//      判断是否包含id 如果有id的话就是修改需要先删除原先的文章素材关联关系
        if(dto.getId()!=null){
            deleteRelation(dto.getId());

        }
        WmNews news=new WmNews();
        BeanUtils.copyProperties(dto,news);
        news.setUserId(user.getUserId());
        news.setSubmitedTime(new Date());
        news.setCreatedTime(new Date());
        news.setImages(JSON.toJSONString(dto.getImages()));
//       获得前端传过来的图片
        List<ImageDto>imageDtos=getImagesFromContent(news.getContent());
//        判断封面类型是不是自动
        if(dto.getType()==-1){
//            用个数进行分类
            if(imageDtos.size()<=0){
//                无图
                news.setType(0);
            }else if(imageDtos.size()<3){
//                随机挑一张
                news.setType(1);
//                取第一个
                List<ImageDto> dtoList = imageDtos.subList(0, 1);
                news.setImages(JSON.toJSONString(dtoList));
            }else {
                news.setType(3);
//                qu前三个
                List<ImageDto> subList = imageDtos.subList(0,3);
                news.setImages(JSON.toJSONString(subList));

            }


        }
        //            保存文章
        this.saveOrUpdate(news);
//            判断是不是草稿0
        if(dto.getStatus()!=0){
//                添加封面关联
            List<ImageDto>coverImages = JSON.parseArray(news.getImages(),ImageDto.class);
            saveRelation(coverImages,news.getId(),1);
//                添加关联内容
            saveRelation(coverImages,news.getId(),0);
            System.out.println(Thread.currentThread().getName() + " 开始调用自动审核服务...");
            auditService.audit(news);

        }


        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.upDownTopic}")
    private  String upDownTopic;

    //文章的上下架
    @Override
    public ResponseResult changeEnable(WmNewsDto dto) {
//        根据id查询文章
        WmNews wmNews=this.getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);

        }
//        修改状态
        wmNews.setEnable(dto.getEnable()==1?true:false);
        this.updateById(wmNews);
        // 同步状态到article
        // 发送消息到kafka
        String key=wmNews.getArticleId().toString();

        String value=dto.getEnable().toString();
        kafkaTemplate.send(upDownTopic,key,value);


        return ResponseResult.okResult();
    }
//人工审核
    @Override
    public ResponseResult auth(NewsAuthDto dto,int type) {
        WmNews wmNews = this.getById(dto.getId());
//        不通过
        if(type==0){
            wmNews.setStatus(2);
            wmNews.setReason(dto.getMsg());
            this.updateById(wmNews);
        }else {
            wmNews.setStatus(4);
            this.updateById(wmNews);
//            继续走自动审核
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }


    //添加内容和封页关联
    @Autowired
    IWmNewsMaterialService newsMaterialService;
    private void saveRelation(List<ImageDto> coverImages, Integer id, int i) {
    int ord=0;
        for (ImageDto dto:coverImages
             ) {
            WmNewsMaterial entity = new WmNewsMaterial();
            entity.setNewsId(dto.getId());
            entity.setNewsId(id);
            entity.setType(i);
            entity.setOrd(ord);
            newsMaterialService.save(entity);
            ord++;



        }




    }

//   从前端传递的内容中提取图片


    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> contentImages = new ArrayList<>();
        List<ContentDto> conditions = JSON.parseArray(content, ContentDto.class);
        for (ContentDto dto : conditions) {
            if(dto.getType().equals("image")){
                String url = dto.getValue();
                Integer id = dto.getId();
                ImageDto imageDto = new ImageDto(id, url);
                contentImages.add(imageDto);

            }

        }
        return contentImages;


    }

    @Autowired
    IWmMaterialService materialService;
//删除素材关联
    private void deleteRelation(Integer id) {
        LambdaQueryWrapper<WmMaterial> query=new LambdaQueryWrapper<>();
        query.eq(WmMaterial::getId,id);
        materialService.remove(query);

    }


}
